<?php
use app\common\config\autoreply_config;
use app\common\helper\index_msg_helper;
use app\common\helper\autoreply_helper;
use app\common\helper\appmsg_helper;
?>
{include file="../app/common/admin/lib/header.html"  title="自动回复"}
{include file="../app/autoreply/view/lib/top_menu.html"}
<div class="rlbox">
  <!--start:关键词添加-->
  <div class="page-header clearfix">
    <div class="page-header-intro left">在这里设置：通过匹配用户输入的内容，来自动回复<br>例如：当用户输入“会员”，来找是否设置了会员关键词，如果有，则回复对应的信息</div>
    <a href="{:url('/autoreply/admin/3')}" class="btn btn-default btn-sm right">&lt;&nbsp;返回关键词自动回复</a>
  </div>
  <form action="{:url('/autoreply/save/3')}" method="post" class="js_createForm">
    <table class="list-table add-table table table-sm" cellpadding="0" cellspacing="0">
      <thead>
        <tr>
          <th>规则名：<span style="font-weight:normal; color:#aaa;">（最多60个字） </span></th><!-- width="232"-->
          <th>&nbsp;</th>
        </tr>
        <tr>
          <td colspan="2" style="padding:10px 10px 10px 20px;">
            <input type="hidden" name="id" value="{$key_info.id}">
            <input type="text" value="{$key_info.title}" class="txt1 js_title">
          </td>
        </tr>
        <tr>
          <th style="width:229px">关键词</th>
          <th>关键词对应的回复</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td colspan="2">
            <div class="clearfix" style="min-height:200px;">
              <div class="keyword-area left">
                <p>在这里输入要匹配的关键词，<br>每个关键词最多30个字</p>
                <div class="js_keyBox">
                  {$key_list = autoreply_helper::get_autoreply_key_list($key_info.id, 2)}
                  {if $key_list}
                    {foreach $key_list as $k=>$v}
                      <div class="per-keywords js_perKeyBox" data-id="{$v.id}" data-match="{$v.match_type}">
                        <i class="icon-reply-del js_deleteKey"></i>
                        <input type="text" value="{$v.title}" class="txt1 js_key" style="width:120px;">
                      </div>
                    {/foreach}
                  {/if}
                </div>
                <div>
                  <a href="javascript:void(0);" class="btn btn-success btn-sm js_addNewKey"><i class="icon-add"></i>新增关键词</a>
                </div>
              </div>
              <i class="icon-go left" style="top:0px;"></i>
              <div class="add-reply-list left js_outDiv">
                <p>在这里输入左侧的关键词对应的回复的信息<br>可以加多条回复，左侧相对应的关键词会从这里随机选一条</p>
                {$auto_content_list = autoreply_helper::get_autoreply_content_list($key_info.id, 2)}
                <!--{$content_count = count($auto_content_list)}-->
                {if $auto_content_list}
                  {foreach $auto_content_list as $k=>$v}
                    <div class="reply-area js_contentDiv" data-id="{$v.id}" data-type="{$v.content_type}" {if $v.content_type != 1}data-content='{$v.content}' style="width:260px;"{/if}>
                      <i class="icon-reply-del js_deleteContent"></i>
                      {if $v.content_type == 0}
                        {widget model="index_msg" func="get_info" file="index_msg_info.html"}
                      {elseif $v.content_type == 1 || $v.content_type == 40}
                        <!--{/*<textarea name="info[cinfo{$k}][content]">{$v.content}</textarea>*/}-->
                        <div contentEditable="true" class="content-textarea js_replyContent">{$v.content}</div>
                        <div class="txt-options clearfix">
                          <p class="txt-count right js_fontNumBox">还可输入<span style="color:green; font-weigth:bold;">300</span>字</p>
                        </div>
                      {elseif $v.content_type == 2 /}
                        {$list = appmsg_helper::get_list(['type'=>1, 'id' => $v.content])}
                        {$flag = 1}
                        {include file="../app/appmsg/view/lib/single_info.html"}
                      {elseif $v.content_type == 3 /}
                        {$list = appmsg_helper::get_list(['type'=>2, 'id' => $v.content])}
                        {$flag = 1}
                        {include file="../app/appmsg/view/lib/multi_info.html"}
                      {elseif $v.content_type == 4 /}
                        <!--{/*widget model="appmsg" func="get_serialize_automsg" file="automsg.html" content=$v.content return_son_list=1*/}-->
                      {/*纯图片*/}
                      {elseif $v.content_type == 10}
                        <!--{/*widget model="appmedia" func="get_list" file="single_info.html" id=$v.content type=10 assign=aaa*/}-->
                      {/*声音*/}
                      {elseif $v.content_type == 20}
                        <!--{/*widget model="appmedia" func="get_list" file="single_info.html" id=$v.content type=20 assign=aaa*/}-->
                      {/if}
                    </div>
                  {/foreach}
                {/if}
                <p class="js_addP"><a href="javascript:void(0);" class="btn btn-success btn-sm js_addNewContent"><i class="icon-add"></i>新增一条回复</a></p>
              </div>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
    <div><button type="submit" class="btn btn-success js_submit">&nbsp;&nbsp;确&nbsp;认&nbsp;&nbsp;</button></div>
  </form>
  <!--end:关键词添加-->
</div>

{include file="../app/common/admin/lib/app_custom_select.html"}
{js href="./static/js/fcd/jquery.fcbkcomplete.js"}
{css href="./static/js/fcd/style.css"}
{js href="./static/js/appCustomSelect.js"}
<script>
var fillTitle = "标题 （必填）";
$(function(){
  
  //inputPlaceHold($(".js_title"), fillTitle, "{$key_info.title}");
  
  // 初始化字数
  $.each($(".js_replyContent"), function(i, n){
    syncNum($(this), $(this).next().find(".js_fontNumBox"), 300);
    
    $(this).keyup(function(){
     syncNum($(this), $(this).next().find(".js_fontNumBox"), 300);
    });
  })
  
  // 添加关键词
  $(".js_addNewKey").click(function(){
    $(".js_keyBox").append('<div class="per-keywords js_perKeyBox" data-match="1"><i class="icon-reply-del js_deleteKey"></i><input type="text" value="" class="txt1 js_key" style="width:120px;"></div>');
  });
  
  // 删除一个关键词
  $('.js_deleteKey').live('click', function(e){
    var thisObj = $(this);
    showConfirm('您确定要删除这个关键词吗?', 1, function(){
      thisObj.closest('.js_perKeyBox').remove();
    });
  });
  
  // 添加新的回复
  $('.js_addNewContent').click(function(e){
    var thisObj = $(this);
    var _offset = thisObj.offset();
    var _top = _offset.top+44;
    var _left = _offset.left;

    $(".js_menuSetBox").find(".js_menuLinkBtn").remove();
    $(".js_menuSetBox .inner-linkpop").find("i").css({ 'left':'12px' }).end().find("b").css({ 'left':'12px' });
    $(".js_menuSetBox").css({ 'top':_top+'px', 'left':_left+'px' }).show();
    
  });
  
  // 关联到首页
  $(".js_menuIndexBtn").live('click', function(){
    $(".js_menuSetBox").hide();
    showConfirm('您确定要关联此菜单到微官网首页吗?', 1, function(){
      if (typeof qDialog != 'undefined') {
        qDialog.close();
      }
      
      showLoading();
      $.post(siteUrl+'/index_msg/admin/load_index_msg', { }, function(json){
        hideLoading();  
        if (json.info != 'ok') {
          showMsg(json.info);
          return;
        }
        
        var html = '<div class="reply-area js_contentDiv" data-type="0" data-content="-1"><i class="icon-reply-del js_deleteContent"></i>';
        html += json.html;
        html += '</div>';
        
        $(html).insertBefore('.js_addP').children('div').css({ 'float':'none' }).end().css({ 'width':'260px' }).children('.icon-select').remove();
        
        bindDeleteReplyEvent();
      }, 'json');
    });
  });
  
  // 添加文本
  $(".js_menuTextBtn").click(function(){
    $(".js_menuSetBox").hide();
    var html = '<div class="reply-area js_contentDiv" data-type="1"><i class="icon-reply-del js_deleteContent"></i>\
       <div contentEditable="true" class="content-textarea js_replyContent"></div>\
       <div class="txt-options clearfix">\
      <p class="txt-count right js_fontNumBox">还可输入<span style="color:green; font-weigth:bold;">300</span>字</p>\
    </div></div>';
    $(html).insertBefore('.js_addP');
    //consoleLog($(html));
    // 字数
    $(".js_replyContent:last").keyup(function(){
     syncNum($(this), $(this).next().find(".js_fontNumBox"), 300);
    });
    
    bindDeleteReplyEvent();
  });

    // 添加活动
    $(".js_menuActivityBtn").click(function(){
        $(".js_menuSetBox").hide();
        var html = '<div class="reply-area js_contentDiv" data-type="40"><i class="icon-reply-del js_deleteContent"></i>\
       <div contentEditable="true" class="content-textarea js_replyContent"></div>\
       <div class="txt-options clearfix">\
      <p class="txt-count right js_fontNumBox">还可输入<span style="color:green; font-weigth:bold;">300</span>字</p>\
    </div></div>';
        $(html).insertBefore('.js_addP');
        //consoleLog($(html));
        // 字数
        $(".js_replyContent:last").keyup(function(){
            syncNum($(this), $(this).next().find(".js_fontNumBox"), 300);
        });

        bindDeleteReplyEvent();
    });

    // 添加图文
  $(".js_menuSingleBtn, .js_menuMultiBtn").live('click', function(){
    $(".js_menuSetBox").hide();
    
    if (typeof qDialog != 'undefined') {
      qDialog.close();
    }
    var msgType = 2;
    if ($(this).hasClass("js_menuMultiBtn")) {
      msgType = 3;
    }
    
    var html  = '<div class="float-prompt-con"><p class="float-pic-info">请选择关链到已有的图文信息，或者去&nbsp;<a target="_blank" href="'+siteUrl+'/appmsg/add/'+(msgType-2)+'">添加新的图文信息</a></p>';
        html += '<div class="js_msgList"><img src="'+siteUrl+'/images/loading2.gif"></div></div>';
    ace.dialog({
      'title':'选择图文信息',
      'content':html,
      'init':function(){
        $(".aceDialog").width(960);
        $(".aceContent").height(400);
        $(".aceContent").css('overflow', 'auto');
        
        setTimeout(function(){
          resetDialogPosition($(".aceDialog"));
        }, 10);
        $(".js_msgList").load(siteUrl+'/appmsg/admin/get_msg_list', { 'type':msgType-1 }, function(){
          bindMsgEvent(msgType);
        });
        
        $(".js_msgList .page>a").live('click', function(e){
          e.preventDefault();
          var _href = $(this).attr('href');
          $(".js_msgList").load(_href, { 'type':msgType-1 }, function(){
            bindMsgEvent(msgType);
          });
        });
      },
      'okValue':''
    });
  });
  
  // 添加纯图片
  $(".js_menuImgBtn, .js_menuVoiceBtn").live('click', function(e){
    e.stopPropagation();
    $(".js_menuSetBox").hide();
    
    if (typeof qDialog != 'undefined') {
      qDialog.close();
    }
    var msgType = 3;
    var contentType = 10;
    var notice = '图片'
    if ($(this).hasClass('js_menuVoiceBtn')) {
      contentType = 20;
      notice = '声音';
    }
    
    var html  = '<div class="float-prompt-con"><p class="float-pic-info">请选择关链到已有的'+notice+'信息，或者去&nbsp;<a target="_blank" href="'+siteUrl+'/appmedia/add/'+(msgType-2)+'">添加新的'+notice+'信息</a></p>';
        html += '<div class="js_msgList"><img src="'+siteUrl+'/static/images/loading2.gif"></div></div>';
    ace.dialog({
      'title':'选择纯'+notice+'信息',
      'content':html,
      'init':function(){
        $(".aceDialog").width(960);
        $(".aceContent").height(400);
        $(".aceContent").css('overflow', 'auto');
        
        setTimeout(function(){
          resetDialogPosition($(".aceDialog"));
        }, 10);
        $(".js_msgList").load(siteUrl+'/appmedia/admin/get_media_list', { 'type':contentType }, function(){
          bindMsgEvent(contentType);
          bindVoiceEvent();
        });
        
        $(".js_msgList .page>a").live('click', function(e){
          e.preventDefault();
          var _href = $(this).attr('href');
          $(".js_msgList").load(_href, { 'type':contentType }, function(){
            bindMsgEvent(contentType);
            bindVoiceEvent();
          });
        });
      },
      'okValue':''
    });
  });
  
  // 添加智能回复
  $(".js_menuCustomBtn").click(function(){
    $(".js_menuSetBox").hide();
    
    if (typeof qDialog != 'undefined') {
      qDialog.close();
    }
    var msgType = 4;
    var oldHtml = $(".js_AppCustomHideBox").html();
    $(".js_AppCustomHideBox").html('');
    var tmpSelectData = [];
    qDialog = null;
    ace.dialog({
      'title':'智能回复',
      'content':oldHtml,
      'init':function(){
        $(".aceDialog").width(680);
        //$(".aceContent").height(400);
        $(".aceContent").css('overflow', 'auto');
        
        var currType    = $(".js_typeSelect").val();
        var currSonType = $(".js_sonTypeSelect"+currType).val();
        //var currSearch  = $.trim($("#js_searchInput").val());
        var queryType   = $.trim($(".js_queryType").val());
        var queryNum   = $.trim($(".js_queryNum").val());
        $(".js_typeSelect").change(function(){
          currType = $(this).val();
          $(".js_sonTypeSelect").hide();
          $(".js_sonTypeSelect"+currType).show();
          againLoad();
          changeAddUrl();
        });
        
        $(".js_sonTypeSelect").change(function(){
          againLoad();
          changeAddUrl();
        });
        
        $(".js_queryType").change(function(){
          queryType   = $.trim($(this).val());
          if (queryType == 2) {
            $(".js_customSelectBox").show();
            $(".js_queryNum").hide();
          } else {
            $(".js_customSelectBox").hide();
            $(".js_queryNum").show();
          }
          setTimeout(function(){
            resetDialogPosition($(".aceDialog"));
          }, 10);
          againLoad();
        });
        
        // 拖动选择的顺序
        $(".float-choose-list").sortable({ 
          axis: "y" ,
          opacity: 0.6,
          stop:function(){
          }
        });
        
      },
      'ok':function(){
        if ($(".aceDialog .okBtn").attr('is_post') == 1) {
          showMsg('提交中，请稍候...');return;
        }
        var currType    = $(".js_typeSelect").val();
        var currSonType = $(".js_sonTypeSelect"+currType).val();
        var queryType   = $.trim($(".js_queryType").val());
        var queryNum    = $.trim($(".js_queryNum").val());
        //var currSearch  = $.trim($(".js_searchInput").val());
        var queryInfo = [];
        $(".js_preCustom").each(function(i){
          queryInfo[i] = $(this).attr('data-id');
        });
        var msgTitle = '内容库';
        if (currType == 2) {
          msgTitle = '活动';
        }
        if (queryType == 2) {
          queryNum = queryInfo.length;
        }
        if (queryNum < 1) {
          showMsg('请至少取出一条'+msgTitle+'数据');
          return;
        }
        if (queryNum > 10) {
          showMsg(msgTitle+'数量不能多于10条');
          return;
        }
        
        var postData = { 'type':currType, 'sub_type':currSonType, 'query_type':queryType, 'query_num':queryNum, 
            'info':queryInfo, 'return_son_list':1 };
        $(".aceDialog .okBtn").text('提交中...').attr('is_post', 1);
        $.post(siteUrl+'/appmsg/admin/automsg', postData, function(json){
          $(".aceDialog .okBtn").text('确定').attr('is_post', 0);
          if (json.info != 'ok') {
            showMsg(json.info);
            return false;
          }
          
          // 成功后的操作
          var html = '<div class="reply-area js_contentDiv" data-type="'+msgType+'" data-content=\''+json.content+'\'><i class="icon-reply-del js_deleteContent"></i>';
          html += json.html;
          html += '</div>';
          
          $(html).insertBefore('.js_addP').children('div').css({ 'float':'none' }).end().css({ 'width':'260px' }).children('.icon-select').remove();
          
          bindDeleteReplyEvent();
          
          $(".js_AppCustomHideBox").html(oldHtml);
          qDialog.close();
        }, 'json');
      },
      'close':function(){
        $(".js_AppCustomHideBox").html(oldHtml);
        //qDialog.close();
      }
    });
  });
  
  // 提交回复
  var isPost = 0;
  $('.js_submit').click(function(e){
    e.preventDefault();
    if (isPost == 1) {
      showMsg('数据提交中，请稍候 ...');
      return false;
    }
    
    var id    = $(":input[name='id']").val();
    var title = $.trim($(".js_title").val());
    if (!title || title == fillTitle) {
      showMsg('请为关键词起一个规则名，最多60个字');
      return;
    }
    if (getNum($(".js_title"), 1) > 60) {
      showMsg('规则名不能超过60个字');
      return;
    }
    
    // 每个关键词
    var keyNum = 0;
    var keyInfo = [];
    var overLimitKey = 0;
    $('.js_perKeyBox').each(function(){
      var thisObj = $(this);
      
      var id        = thisObj.attr('data-id');
      var key       = $.trim(thisObj.find(".js_key").val());
      var matchType = thisObj.attr('data-match');
      if (!key) {
        return;
      }
      if (getNum(thisObj.find(".js_key"), 1) > 30) {
        overLimitKey = 1;
        return;
      }
      
      keyInfo[keyNum] = { 'id':id, 'title':key, 'match_type':matchType };
      
      keyNum++;
    });
    if (overLimitKey > 0) {
      showMsg('每个关键词不能超过30字');
      return;
    }
    if (keyNum == 0) {
      showMsg('请至少填写一个关键词');
      return;
    }
    
    // 每条回复
    var num = 0;
    var info = [];
    var overLimit = 0;
    $('.js_contentDiv').each(function(){
      var thisObj = $(this);
      var contentId      = thisObj.attr('data-id');
      var type    = thisObj.attr('data-type');
      var content = '';
      if (type == 1 || type == 40) {
        content = $.trim(thisObj.find('.js_replyContent').html());
      } else {
        content = thisObj.attr('data-content');
      }
      //console.log(content, type);
      if (!content) {
        return;
      }
      if (type == 1  || type == 40) {
        var fontNum = getNum(thisObj.find('.js_replyContent'));
        if (fontNum > 300) {
          overLimit = 1;
          return;
        }
        if (fontNum < 0) {
          reutrn;
        }
        
        //console.log(fontNum);
      }
      
      info[num] = { 'id':contentId, 'type':type, 'content':content };
      num++;
    });
    if (overLimit > 0) {
      showMsg('每条回复的内容不能超过300字');
      return;
    }
    if (num == 0) {
      showMsg('请至少填写一条回复内容');
      return;
    }
    
    isPost = 1;
    var postData = { 'id':id, 'title':title, 'key':keyInfo, 'info':info };
    $.post(siteUrl+'/autoreply/save/3', postData, function(json){
      isPost = 0;
      if (json.info != 'ok') {
        showMsg(json.info);
        return;
      }
      
      //showMsg('成功', 1);
      location.href = siteUrl+'/autoreply/admin/3.html';
    }, 'json');
  });
  
  bindDeleteReplyEvent();
});

// 图文列表加载后的事情绑定
function bindMsgEvent(msgType)
{
  $(".js_msgList>li").unbind('click');
  // 选择某一条图文做为回复
  $(".js_msgList>li").bind('click', function(e){
    e.preventDefault();
    e.stopPropagation();
    var thisObj = $(this);
    if (!thisObj.hasClass('curr')) {
      var id = thisObj.attr('data-id');
      if (!id) {
        showMsg('请选择一条信息');
        return false;
      }
      
      showConfirm('您确定要选择该图文信息吗?', 1, function(){
        if ($(".js_contentDiv[data-content='"+id+"']").length > 0) {
          showMsg('已经选择了该条图文信息，无须多次选择');
          return;
        }
        
        var html = '<div class="reply-area js_contentDiv" data-type="'+msgType+'" data-content="'+id+'"><i class="icon-reply-del js_deleteContent"></i>';
        html += thisObj.html();
        html += '</div>';
        
        $(html).insertBefore('.js_addP').children('div').css({ 'float':'none' }).end().css({ 'width':'260px' }).children('.icon-select').remove();
        
        bindDeleteReplyEvent();
        
        qDialog.close();
      });
    }
  });
}

// 绑定回复信息删除事件
function bindDeleteReplyEvent()
{
  $('.js_deleteContent').unbind('click')
//删除一条回复
  $('.js_deleteContent').bind('click', function(e){
    var thisObj = $(this);
    showConfirm('您确定要删除这条回复吗?', 1, function(){
      thisObj.closest('.js_contentDiv').remove();
    });
  });
}

// 加载自定义浮层信息列表
function loadCustomSelectList(currType, currSonType, currSearch)
{
  var _url = siteUrl+'/';
  if (currType == 1) {
    _url += 'article/admin/load_article?per_page=8&title='+currSearch;
  } else if (currType == 2) {
    _url += 'article/admin/load_article?per_page=8&type='+currType+'&title='+currSearch;
  }
  $(".js_loadBox").load(_url, {  }, function(){
    setTimeout(function(){
      resetDialogPosition($(".aceDialog"));
    }, 10);
  });
}
//绑定语音事件
function bindVoiceEvent()
{
  $(".js_perVoiceMedia").unbind('click');
  
  $(".js_perVoiceMedia").bind('click', function(e){
    e.stopPropagation();
    var id = $(this).attr('data-id');
    
    document.getElementById('js_noticeMusic'+id).play();
  });
}
</script>
{include file="../app/common/admin/lib/footer.html"}